//
//  TopicViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "TopicViewController.h"
#import "myCell.h"
#import "MJRefresh.h"
#import "AsyncConnection.h"
#import "define.h"
#import "UIImageView+WebCache.h"
#import "ImageSaveViewController.h"


@interface TopicViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSMutableArray *commArr;
@property (nonatomic, retain) NSDictionary *dic;

@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, assign) CGFloat offHeight;


@end

@implementation TopicViewController

- (void)dealloc
{
    [_table release];
    [_array release];
    [_commArr release];
    [_dic release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self async];
    self.navigationItem.hidesBackButton = YES;
    
    self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
    self.offHeight = [[UIScreen mainScreen]bounds].size.height / 667;
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(10 *_offWidth, 0, 40 *_offWidth, 40 *_offHeight)];
    button.tag = 111;
    [button addTarget:self action:@selector(fanhui:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *like = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 50 *_offWidth, 0, 40 *_offWidth, 40 *_offHeight)];
    like.tag = 222;
    
    [like setImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];
    
    
    for (UIButton *button in self.navigationController.navigationBar.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            button.hidden = YES;
        }
    }
    

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(fanhui:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];

    [button setImage:[UIImage imageNamed:@"f.png"] forState:UIControlStateNormal];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
   
}

- (void)fanhui:(UIBarButtonItem *)button
{

    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (void)async
{
    NSDictionary *dic = @{@"gv":@"6.3.0",
                          @"gf":@"iphone",
                          @"gs":@"640x1136",
                          @"more_items":@"1",
                          @"width":@"320",
                          @"topic_id":self.tid,
                          @"twm":@"1"};
        [AsyncConnection asyncConnection:TOPIC_DETAIL parmaters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            self.dic = [dic objectForKey:@"data"];
        self.array= [[dic objectForKey:@"data"]objectForKey:@"items"];
            [self commentConnection];
        
    }path:@"class_topic_detail"];
}

- (void)commentConnection
{
    NSDictionary *dic = @{@"gv":@"6.3.0",
                          @"gf":@"iphone",
                          @"gs":@"640x1136",
                          @"more_items":@"1",
                          @"type":@"topic",
                          @"topic_id":self.tid,
                          @"rtf":@"1",
                          @"flag":@""};
   
    [AsyncConnection asyncConnection:TOPIC_COMMENT parmaters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.commArr = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self createTableView];
    }path:@"class_topic_comment"];
}


#pragma mark -
#pragma mark 整个一个大的tableview

- (void)createTableView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.table.backgroundColor = [UIColor lightTextColor];
    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.table release];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else{
        return self.array.count;
    }
//    else
//    {
//        return self.commArr.count;
//    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%ld", indexPath.section + indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"%ld", indexPath.section + indexPath.row]];
        
    }
    NSDictionary *dic = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"cells"]objectAtIndex:0];
    if (indexPath.section == 0) {
        
        cell.textLabel.text = [self.dic objectForKey:@"title"];
        UILabel *date = [[UILabel alloc]initWithFrame:CGRectMake(20 *_offWidth, 70*_offHeight, 180 *_offWidth, 20 *_offHeight)];
        UIButton *comm = [[UIButton alloc]initWithFrame:CGRectMake(170 *_offWidth, 70 *_offHeight, 50 *_offWidth, 20 *_offHeight)];
        [cell.contentView addSubview:date];
        date.textColor = [UIColor lightGrayColor];
        date.font = [UIFont systemFontOfSize:13];
        [cell.contentView addSubview:comm];
        [comm setImage:[UIImage imageNamed:@"comm.png"] forState:UIControlStateNormal];
        comm.titleLabel.font = [UIFont systemFontOfSize:13];
        [comm setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [comm setTitle:[self.dic objectForKey:@"commentCount"] forState:UIControlStateNormal];
        date.text = [self.dic objectForKey:@"dateTime"];
        [date release];
        [comm release];
    }
    if (indexPath.section == 1) {
        
        if ([[[dic objectForKey:@"component"] objectForKey:@"componentType"]isEqualToString:@"word"]) {
            cell.textLabel.numberOfLines = 0;
            cell.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * [[dic objectForKey:@"height"]floatValue] / [[dic objectForKey:@"width"]floatValue] + 60);
            cell.textLabel.text = [[dic objectForKey:@"component"]objectForKey:@"content"];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.textLabel.textColor = [UIColor darkGrayColor];
        }
        if ([[[dic objectForKey:@"component"] objectForKey:@"componentType"] isEqualToString:@"cell"]) {
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * [[dic objectForKey:@"height"]floatValue] / [[dic objectForKey:@"width"]floatValue])];
            image.userInteractionEnabled = YES;
            image.tag = indexPath.row;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(save:)];
            [image addGestureRecognizer:tap];
            [tap release];
            cell.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * [[dic objectForKey:@"height"]floatValue] / [[dic objectForKey:@"width"]floatValue]);
            [cell.contentView addSubview:image];
            NSString *pic = [[dic objectForKey:@"component"]objectForKey:@"picUrl"];
            NSArray *arr = [pic componentsSeparatedByString:@"?"];
            [image sd_setImageWithURL:[NSURL URLWithString:[arr objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        }
        if ([[[dic objectForKey:@"component"] objectForKey:@"componentType"] isEqualToString:@"linkDecoratedCell"]) {
            
             NSDictionary *dic1 = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"cells"]objectAtIndex:0];
            
            UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, (self.view.frame.size.width - 10) / 2, (self.view.frame.size.width - 10) / 2 * [[dic1 objectForKey:@"height"]floatValue] / [[dic1 objectForKey:@"width"]floatValue])];
            image1.userInteractionEnabled = YES;
           
        cell.frame =  cell.frame = CGRectMake(0, 0, self.view.frame.size.width, (self.view.frame.size.width - 10) / 2 * [[dic1 objectForKey:@"height"]floatValue] / [[dic1 objectForKey:@"width"]floatValue]);
            [cell.contentView addSubview:image1];
            NSString *pic = [[dic1 objectForKey:@"component"] objectForKey:@"picUrl"];
            NSArray *arr = [pic componentsSeparatedByString:@"?"];
            [image1 sd_setImageWithURL:[NSURL URLWithString:[arr objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
            
            
            NSDictionary *dic2 = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"cells"]objectAtIndex:0];
            
            UIImageView *image2 = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 10) / 2 + 10, 0, (self.view.frame.size.width - 10) / 2, (self.view.frame.size.width - 10) / 2 * [[dic2 objectForKey:@"height"]floatValue] / [[dic2 objectForKey:@"width"]floatValue])];
            cell.frame =  cell.frame = CGRectMake(0, 0, self.view.frame.size.width, (self.view.frame.size.width - 10) / 2 * [[dic2 objectForKey:@"height"]floatValue] / [[dic2 objectForKey:@"width"]floatValue]);
            [cell.contentView addSubview:image2];
            NSString *pic1 = [[dic2 objectForKey:@"component"] objectForKey:@"picUrl"];
            NSArray *arr1 = [pic1 componentsSeparatedByString:@"?"];
            [image2 sd_setImageWithURL:[NSURL URLWithString:[arr1 objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
            
            
            
           
           
        }
    }
    
    

    
    
    return cell;
}

- (void)save:(UITapGestureRecognizer *)save
{
    ImageSaveViewController *iiii = [[ImageSaveViewController alloc]init];
    iiii.image = ((UIImageView *)save.view).image;
    CGFloat height = [[[[[self.array objectAtIndex:save.view.tag] objectForKey:@"cells"]objectAtIndex:0] objectForKey:@"height"]floatValue];
    CGFloat width = [[[[[self.array objectAtIndex:save.view.tag]objectForKey:@"cells"]objectAtIndex:0] objectForKey:@"width"]floatValue];
    iiii.width = width;
    iiii.height = height;
    [self.navigationController pushViewController:iiii animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10 *_offHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 100 *_offHeight;
    }if (indexPath.section == 1) {
         NSDictionary *dic = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"cells"]objectAtIndex:0];
        if ([[[dic objectForKey:@"component"] objectForKey:@"componentType"] isEqualToString:@"linkDecoratedCell"]) {
            return (self.view.frame.size.width - 10) / 2 * [[dic objectForKey:@"height"]floatValue] / [[dic objectForKey:@"width"]floatValue];
        } else
        {
        return self.view.frame.size.width * [[dic objectForKey:@"height"]floatValue] / [[dic objectForKey:@"width"]floatValue];
        }
    }
    else
    {
        return 200 *_offHeight;
    }
}

#pragma mark -
#pragma mark - 计算文字高度
+ (CGFloat)heightWithText:(NSString *)text
{
    // 参数1: 预定的矩形大小
    // 参数2: 图形选项
    // 参数3: 属性字典(设置字体大小, 一般和cell中的设置成一样的)
    // 参数4: 内容文本 一般设置为空nil
    CGRect rect = [text boundingRectWithSize:CGSizeMake(280 * [[UIScreen mainScreen]bounds].size.width / 375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    return rect.size.height;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
